#include "head.h"
#include "taskQueue.h"
#include "epollFunc.h"

int exitpipe[2];
int initThreadPool(threadPool_t* pthreadPool,int workerNum){
    pthreadPool->workerNum=workerNum;
    pthreadPool->tidArry=(pthread_t*)calloc(pthreadPool->workerNum,sizeof(pthread_t));
    initQueue(&pthreadPool->taskQueue);//初始化队列
    pthread_mutex_init(&pthreadPool->mutex,NULL);
    pthread_cond_init(&pthreadPool->cond,NULL);
    pthreadPool->exitflag=0;
    return 0;
}
void sigFunc(int signum){
    printf("父进程关闭\n");
    write(exitpipe[1],"1",1);
}
int main(int argc,char* argv[]){
    //./server 192.168.88.129 1234 4
    if(argc<4){
        error(1,0,"参数数目缺失\n");
    }
    int workerNum=atoi(argv[3]);
    //父进程复制关闭子进程
    pipe(exitpipe);
    if(fork()!=0){
        close(exitpipe[0]);
       // signal(SIGUSR1,sigFunc);
        wait(NULL);
        exit(0);
    }
    //子进程
    close(exitpipe[1]);
    threadPool_t threadPool;

    initThreadPool(&threadPool,workerNum);//初始化线程池数据结构
    //初始化tcp
    int sockfd;
    tcpInit(argv[1],argv[2],&sockfd);
    //以上网络配置和线程池就准备好了
    //这个时候需要启动线程
    makeWorker(&threadPool);
    //创建监听集合
    int epfd=epoll_create(1);
    epollAdd(epfd,sockfd);
    epollAdd(epfd,exitpipe[0]);
    struct epoll_event readySet[1024];
    
    while(1){
        int readyNum=epoll_wait(epfd,readySet,1024,-1);
        for(int i=0;i<readyNum;i++){
            if(readySet[i].data.fd==sockfd){//如果有客户请求
                printf("client is connecting the server\n");
                int netfd=accept(sockfd,NULL,NULL);
                pthread_mutex_lock(&threadPool.mutex);//访问队列要加锁
                enqueue(&threadPool.taskQueue,netfd);
                printf("队列以放入任务\n");
                pthread_cond_signal(&threadPool.cond);

                pthread_mutex_unlock(&threadPool.mutex);//访问队列要加锁
                
            }
            else if(readySet[i].data.fd==exitpipe[0]){
                printf("进程池即将关闭\n");
                pthread_mutex_lock(&threadPool.mutex);
                threadPool.exitflag=1;
                pthread_cond_broadcast(&threadPool.cond);
                pthread_mutex_unlock(&threadPool.mutex);


                //回收资源
                for(int i=0;i<threadPool.workerNum;i++){
                    pthread_join(threadPool.tidArry[i],NULL);
                }
                printf("all worker is done\n");
                pthread_exit(NULL);
            }
        }
        sleep(3);
    }

}
